package fr.emse.tatiana.replayable.tabulardisplay;

import java.io.File;
import java.io.IOException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IEditorPart;

import fr.emse.tatiana.TatianaConstants;
import fr.emse.tatiana.filter.TempFileFactory;
import fr.emse.tatiana.filter.XQueryOut;
import fr.emse.tatiana.replayable.AbstractReplayableEditor;
import fr.emse.tatiana.replayable.ReplayableModel;


public class SaveAsExportedAction extends Action {
	
	IReplayableEditor editor;
	String fname;
	
	public SaveAsExportedAction(String label, String fname) {
		setText(label);
		this.fname = fname;
		// The id is used to refer to the action in a menu or toolbar
		//setId(ICommandIds.CMD_EXPORT);
		// Associate the action with a pre-defined command, to allow key bindings.
		//setActionDefinitionId(ICommandIds.CMD_FILTER);
		//setImageDescriptor(fr.emse.tatiana.Activator.getImageDescriptor("/icons/sample2.gif"));
		this.setEnabled(false);
	}

	public void setEditor(IEditorPart editor) {
		if (editor != null && (editor instanceof IReplayableEditor)) {
			this.editor = (IReplayableEditor) editor;
		} else {
			this.editor = null;
		}
		
		setEnabled(editor != null);
	}

	@Override
	public void run() {
		

		if (editor != null) {
			FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); 
			String path = dialog.open();
			if (path == null) {
				return;
			}
			if (editor.getModel() == null)
			{
				System.err.println("Unable to save display file : table empty");
				return;
			}

			String qresult;
			try { 
				qresult=TempFileFactory.getName();
				ReplayableModel m = new ReplayableModel(editor.getReplayableSaver().getProject());
				m.setContents(editor.getModel(),true);
				m.saveToReplayableFile(qresult);
			} catch (IOException e) {
				// TODO Auto-generated catch block

				e.printStackTrace();
				return;
			}

			try {
				
				IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(TatianaConstants.TATIANA_PROJECT_NAME);

				IFile filterfile = project.getFolder(TatianaConstants.SCRIPTS_FOLDER_NAME).getFile(fname);
				new XQueryOut(
						filterfile.getLocation().toString(),
						new File(qresult).toURI().getPath(),
						path
				);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			TempFileFactory.dispose();
			
		}
	}
}
